import Cookies from 'js-cookie';
import {
  COOKIE_KEY_TOKEN,
  COOKIE_KEY_ATOMGIT_USER,
  COOKIE_DOMAIN_ATOMGIT,
} from './constants';

const AUTH_CODE = [400101];

// 从浏览器中获取 Token
export function getTokenFromClient() {
  return Cookies.get(COOKIE_KEY_TOKEN) ?? '';
}

export function setTokenForClient(token: string) {
  Cookies.set(COOKIE_KEY_TOKEN, token, {
    expires: 30,
    path: '/',
    sameSite: 'Lax',
  });
}

export const clearTokenForClient = () => {
  Cookies.remove(COOKIE_KEY_TOKEN, {
    path: '/',
    sameSite: 'Lax',
  });
};

export const isAuthFailedCode = (code: number) => AUTH_CODE.includes(code);

export function gotoLoginForClient() {
  const location = window.location;
  const from = `${location.pathname}${location.search}${location.hash}`;

  location.href = `/passport/login?from=${encodeURIComponent(from)}`;
}

export function gotoLogoutForClient() {
  const location = window.location;
  const from = `${location.pathname}${location.search}${location.hash}`;

  location.href = `/passport/logout?from=${encodeURIComponent(from)}`;
}

export const isLoginForClient = () => {
  if (import.meta.env.VITE_MOCK_LOGIN === 'yes') {
    return true;
  }
  else {
    return !!getTokenFromClient();
  }
};

export const setAtomGitUserForClient = (user: Record<string, any>) => {
  Cookies.set(COOKIE_KEY_ATOMGIT_USER, JSON.stringify(user), {
    path: '/',
    expires: 180,
    domain: import.meta.env.DEV ? undefined : COOKIE_DOMAIN_ATOMGIT,
  });
}

export const clearAtomGitUserForClient = () => {
  Cookies.remove(COOKIE_KEY_ATOMGIT_USER, {
    path: '/',
    domain: import.meta.env.DEV ? undefined : COOKIE_DOMAIN_ATOMGIT,
  });
}
